package com.ellecity06.cwhiskymall.ui

import com.ellecity06.common.base.BaseMviViewModel
import com.ellecity06.common.ktx.postEvent
import com.ellecity06.common.utils.CommonUtils
import com.ellecity06.common.utils.appContext
import com.ellecity06.cwhiskymall.BuildConfig
import com.ellecity06.cwhiskymall.bean.request.H5UrlRequest
import com.ellecity06.cwhiskymall.bean.request.VersionInfoRequest
import com.ellecity06.cwhiskymall.bean.response.AppVersionResponse
import com.ellecity06.cwhiskymall.http.ServerConfig
import com.ellecity06.cwhiskymall.http.request


/**
 * @author ellecity06
 * @time 2023/4/15 11:01
 * @des
 */
class MainViewModel : BaseMviViewModel<MainState, MainIntent>() {
    private var versionResponse: AppVersionResponse? = null
    private val versionCode: Int by lazy { CommonUtils.getVersionCode(appContext) }
    override suspend fun collectIntent(it: MainIntent) {
        when (it) {
            MainIntent.FetchLastVersion -> {
                lastVersion()
            }

            MainIntent.FetchH5Host -> {
                fetchH5()
            }
        }
    }

    private fun fetchH5() {
        if (!BuildConfig.SERVER_RELEASE) return
        request(api = { getBatchH5RequestUrl(H5UrlRequest("h5_register_url,h5_order_url,h5_caewap_url")) }, success = {
            if (it != null) {
                if (it.h5_order_url != null) {
                    ServerConfig.baseH5Host = "${it.h5_order_url}/#/"
                }
                if (it.h5_register_url != null) {
                    ServerConfig.baseIpH5Host = "${it.h5_register_url}/#/"
                }
                if (it.h5_caewap_url != null) {
                    ServerConfig.baseCaewapH5Host = "${it.h5_caewap_url}/#/"
                }
            }

        },  error = {

        })
    }

    private fun lastVersion() {
        request(api = { lastVersion(VersionInfoRequest()) }, success = {
            if (it != null) {
                versionResponse = it
                if (versionCode > 0 && versionCode < it.versionNum) {
                    mState.postEvent(MainState.ShowDialog(versionResponse!!))
                }
            }

        }, error = {

        })
    }

}